const env = process.env.NODE_ENV
require('es6-promise').polyfill();
require('isomorphic-fetch');

// 取queryString
export function getParameterByName (name, url) {
    if (!url) {
        url = window.location.href
    }
    name = name.replace(/[\[\]]/g, '\\$&')
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url)
    if (!results) return null
    if (!results[2]) return ''
    return decodeURIComponent(results[2].replace(/\+/g, ' '))
}

// DateTransformer
export function utcToDate (timestamp) {
    timestamp = timestamp * 1000
    let y = new Date(timestamp).getFullYear(),
        m = new Date(timestamp).getMonth() + 1,
        d = new Date(timestamp).getDate(),
        h = new Date(timestamp).getHours(),
        mm = new Date(timestamp).getMinutes()
    const m0 = m
    m = m < 10 ? '0' + m : m
    mm = mm < 10 ? '0' + mm : mm
    h = h < 10 ? '0' + h : h
    if (y === new Date().getFullYear()) return m0 + '月' + d + '日 ' + h + ':' + mm
    else return y + '年' + m + '月' + d + '日 ' + h + ':' + mm
}

// myalert
export function myAlert (txt) {
    let div0 = document.createElement('div'),
        div = document.createElement('div')
    div.innerHTML = txt
    div.classList.add('my-alert')
    div0.appendChild(div)
    div0.classList.add('my-alert-container')
    document.querySelector('body').appendChild(div0)
    setTimeout(() => {
        document.querySelector('body').removeChild(div0)
    }, 1500)
}

export function loadMore ({
    el = '',
    cb = function () {}
}) {
    this.el = el
    this.cb = cb
    this.loading = false
    loadMore.prototype.toEnd = function () {
        // documen.body.scrollTop在chomre下居然一直为0！
        var scrollTop = this.el ? this.el.scrollTop : window.scrollY,
            pageHeight = this.el ? this.el.getBoundingClientRect().height : window.innerHeight,
            scrollHeight = this.el ? this.el.scrollHeight : document.body.scrollHeight
        if (scrollTop + pageHeight > scrollHeight - 5) {
            if (this.loading) return
            this.loading = true
            this.cb()
        }
    }
    loadMore.prototype.open = function () {
        this.listener = this.toEnd.bind(this)
        this.el ? this.el.addEventListener('scroll', this.listener, false) : window.addEventListener('scroll', this.listener, false)
    }
    loadMore.prototype.close = function () {
        this.el ? this.el.removeEventListener('scroll', this.listener, false) : window.removeEventListener('scroll', this.listener, false)
    }
}

export function handleHistory (router, historyUrl) {
    const thisUrl = location.href
    history.pushState(null, null, thisUrl)
    // 问题来了 从后一个链接跳回来的popstate locaation.href也是当前链接啊！
    const changeHistory = () => router.replace(historyUrl)
    window.addEventListener('popstate', function (e) {
        // console.log(e)
        // if (location.href === thisUrl)
    })
}

function request (data, config) {
    function serialize (obj) {
        var str = []
        for (var p in obj) {
            if (obj.hasOwnProperty(p)) {
                str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]))
            }
        }
        return str.join('&')
    }

    const fetchPromise = new Promise((resolve, reject) => {
        let baseURL = 'http://we.hzchuangxiangzhe.cn/wukong/php/PcApi'
        if (config && config.url2) baseURL = 'http://we.hzchuangxiangzhe.cn/shopping_zhou/php/PcApi'
        if (env === 'development') baseURL = 'https://easy-mock.com/mock/5a0a567bb31e3216824d6a7d/shopping'

        const reqURL = env === 'development' ? `${baseURL}/${data.name}` : baseURL
        const credentials = env === 'development' ? '' : 'include'

        let headers = new Headers()

        headers.append('Content-Type', 'application/x-www-form-urlencoded')
        fetch(reqURL, {
            method: 'POST',
            headers,
            credentials,
            body: serialize(data)
        }).then(r => r.json()).then(obj => resolve(obj)).catch(err => reject(err))
    })

    // 网络连接问题
    const abortPromise = new Promise((resolve, reject) => {
        setTimeout(reject, 80000, 'timeout')
    })

    return Promise.race([fetchPromise, abortPromise])
}

export async function myFetch (data, config) {
    try {
        const res = await request(data, config)
        return res
    } catch (err) {
        const msg = err === 'timeout' ? '网络连接异常，请稍后刷新重试' : '后台出错了~'
        return { success: false, msg }
    }
}
